package com.key.service.impl;

import com.key.common.R;
import com.key.common.TranException;
import com.key.common.vo.AssetFieldAndBusinessVO;
import com.key.entity.AssetField;
import com.key.entity.AssetType;
import com.key.entity.AssetTypeBusiness;
import com.key.mapper.AssetTypeMapper;
import com.key.mapper.GeneralMapper;
import com.key.service.GeneralService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class GeneralServiceImpl implements GeneralService {
    @Autowired
    private GeneralMapper generalMapper;
    @Autowired
    private AssetTypeMapper assetTypeMapper;
    @Override
    public R findCheckedAssetField() {
        List<AssetField> allAssetFields = generalMapper.findAllAssetField();
        R r=R.ok();
        r.setData(allAssetFields);
        return r;
    }

    @Override
    public R findCheckedAssetType() {
        List list=new ArrayList();
        for (int i = 1; i <5 ; i++) {
            List<AssetTypeBusiness> assetTypeBusinesses = generalMapper.findCheckedAssetType(i);
            for (AssetTypeBusiness assetTypeBusiness : assetTypeBusinesses) {
                AssetType assetType = assetTypeMapper.findAssetTypeById(assetTypeBusiness.getAssetTypeId());
                assetTypeBusiness.setName(assetType.getAssetTypeName());
            }
            list.add(assetTypeBusinesses);
        }
        R r=R.ok();
        r.setData(list);
        return r;
    }

    @Override
    public R commitService(AssetFieldAndBusinessVO assetFieldAndBusinessVO) {
        List<AssetField> assetFields = assetFieldAndBusinessVO.getAssetFields();
        List<List<AssetTypeBusiness>> assetTypeBusinesses = assetFieldAndBusinessVO.getAssetTypeBusinesses();
        try {
            generalMapper.deleteAssetField();
            for (AssetField assetField : assetFields) {
                generalMapper.insertAssetField(assetField);
            }
            generalMapper.deleteAssetTypeBusiness();
            for (List<AssetTypeBusiness> assetTypeBusiness : assetTypeBusinesses) {
                for (AssetTypeBusiness typeBusiness : assetTypeBusiness) {
                    generalMapper.insertAssetTypeBusiness(typeBusiness);
                }
            }
            return R.ok();
        }catch (Exception e){
            throw new TranException("提交失败");
        }

    }
}
